import javax.sql.DataSource;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

//服务器
public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int id) throws SocketException {
        socket = new DatagramSocket(id);
    }

    public void stack() throws IOException {
        System.out.println("启动服务器!");
        while(true) {
            //读取请求
            DatagramPacket packet = new DatagramPacket(new byte[4096],4096);
            socket.receive(packet);

            //解析请求
            String str = new String(packet.getData(),0, packet.getLength());

            //请求回应
            String str1 = Persson(str);

            //构建响应数据
            DatagramPacket packet1 = new DatagramPacket(str1.getBytes(),str1.getBytes().length,packet.getSocketAddress());

            //响应请求
            socket.send(packet1);

            //显示请求响应数据
            System.out.printf("[%d:%s] %s %s\n",packet.getPort(),packet.getAddress().toString(),str,str1);
        }
    }

    public String Persson(String str) {
        return str;
    }
    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(2000);
        server.stack();
    }
}
